package com.lagou.payrabbitmq.controller;

import com.lagou.payrabbitmq.cache.CancelOrderCache;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.UUID;

/**
 * PayController
 *
 * @author zyt
 * @since 2020/11/14 23:08
 */
@Controller
public class PayController {

    @Autowired
    private AmqpTemplate rabbitTemplate;


    /**
     * 下单
     * @param productName
     * @return
     */
    @RequestMapping("/placeOrder")
    public ModelAndView placeOrder(String productName) {

        // 模拟订单入库
        String id = UUID.randomUUID().toString();
        // 放入待支付队列
        rabbitTemplate.convertAndSend("ex.pay","key.pay",id + "--" + productName);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("orderId", id);
        modelAndView.addObject("productName", productName);
        modelAndView.setViewName("pay");
        return modelAndView;
    }

    /**
     * 支付
     * @param orderId
     * @return
     */
    @RequestMapping("/pay")
    public ModelAndView pay(String orderId) {
        ModelAndView modelAndView = new ModelAndView();
        if (CancelOrderCache.cancelOrder.containsKey(orderId)) {
            modelAndView.setViewName("cancelOrderList");
            modelAndView.addObject("cancelOrders", CancelOrderCache.cancelOrder);
        } else {

            // 消费消息
            Object o = rabbitTemplate.receiveAndConvert("q.pay");
            String msg = o.toString();
            String[] split = msg.split("--");
            String productName = split[1];
            modelAndView.addObject("orderId", orderId);
            modelAndView.addObject("productName", productName);
            modelAndView.setViewName("pay-success");
        }
        return modelAndView;
    }


}
